package com.zaker.touchtv.modules.live;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.drawable.GradientDrawable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.zaker.touchtv.R;
import com.zaker.touchtv.component.PlayPauseDrawable;
import com.zaker.touchtv.component.PlayPauseView;

import static com.zaker.touchtv.utils.Constants.DEFAULT_PLAY_ASPECT_RATIO;

public class LiveMainLayout extends FrameLayout {

  private final String LOG_TAG = "LiveMainLayout";

  private final static float SURFACE_MAX_RATIO = 3 / 4f;

  private final static int LIVE_ASSISTANT_TOOLBAR_SIZE = 60;//dp

  private final static int ASSISTANT_TOOLBAR_ITEM_COUNT = 6;

  SurfaceView mLivePlaySurfaceView;
  private ContentLoadingProgressBar mLivePlayLoadingView;
  private PlayPauseView mLivePlayStartBtn;
  private View[] assistantToolbarItems = new View[ASSISTANT_TOOLBAR_ITEM_COUNT];
  private TextView liveStateTip;

  private int[][] assistantItemSeparators = new int[ASSISTANT_TOOLBAR_ITEM_COUNT][4];
  private PaintFlagsDrawFilter mAdjustLineDrawFilter;
  private Paint mSeparatorLinePaint;
  private int separatorSize;
  private int liveStateTipTopMargin;
  private GradientDrawable shapeDrawable;

  private float mPlayAspectRatio = DEFAULT_PLAY_ASPECT_RATIO;

  public static LiveMainLayout newInstance(@NonNull LayoutInflater layoutInflater,
                                           @Nullable ViewGroup rootViewGroup,
                                           boolean attachToRoot) {
    View resultView = layoutInflater.inflate(R.layout.live_main_layout, rootViewGroup, attachToRoot);
    if (attachToRoot) {
      return (LiveMainLayout) resultView.findViewById(R.id.live_main_content);
    } else {
      return (LiveMainLayout) resultView;
    }
  }

  public LiveMainLayout(Context context, AttributeSet attrs) {
    super(context, attrs);

    setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT,
        LayoutParams.MATCH_PARENT));
    separatorSize = getResources().getDimensionPixelSize(R.dimen.divider_height);
    mSeparatorLinePaint = new Paint();
    mSeparatorLinePaint.setAntiAlias(false);
    int lineColor = ResourcesCompat.getColor(getResources(), R.color.colorDivider, null);
    mAdjustLineDrawFilter = new PaintFlagsDrawFilter(0, Paint.FILTER_BITMAP_FLAG);
    mSeparatorLinePaint.setColor(lineColor);
    mSeparatorLinePaint.setStrokeWidth(separatorSize);
    liveStateTipTopMargin = getResources().getDimensionPixelOffset(R.dimen.live_tip_top_margin);
  }

  @Override
  protected void onFinishInflate() {
    super.onFinishInflate();
    mLivePlaySurfaceView = (SurfaceView) getChildAt(0);
    mLivePlayLoadingView = (ContentLoadingProgressBar) getChildAt(1);
    mLivePlayStartBtn = (PlayPauseView) getChildAt(2);
    mLivePlayStartBtn.setInitState(true);
    for (int i = 3; i < 3 + ASSISTANT_TOOLBAR_ITEM_COUNT; i++) {
      assistantToolbarItems[i - 3] = getChildAt(i);
    }
    liveStateTip = (TextView) getChildAt(3 + ASSISTANT_TOOLBAR_ITEM_COUNT);
    liveStateTip.setVisibility(GONE);
    setLiveStateTipBackground();
  }

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    //控件总宽
    int widthHint = MeasureSpec.getSize(widthMeasureSpec);
    int heightHint = MeasureSpec.getSize(heightMeasureSpec);
//    int availableWidth = widthHint - ViewCompat.getPaddingStart(this)
//        - ViewCompat.getPaddingEnd(this);

    Log.i(LOG_TAG, " heightHint: " + heightHint + " getTop: " + getTop()
        + " getPaddingTop: " + getPaddingTop());

    heightHint -= getTop() + getPaddingTop();

    if (widthHint < heightHint) {
      measureVertical(widthHint, heightHint, widthMeasureSpec, heightMeasureSpec);
    } else {
      measureHorizontal(widthHint, heightHint, widthMeasureSpec, heightMeasureSpec);
    }
  }

  private void measureHorizontal(int widthHint, int heightHint,
                                 int widthMeasureSpec, int heightMeasureSpec) {
    //直播录制区域
    final LayoutParams playSurfaceParams = (LayoutParams) mLivePlaySurfaceView.getLayoutParams();
    int playSurfaceHeight = heightHint;
    int playSurfaceWidth = (int) (heightHint * mPlayAspectRatio);
    if (playSurfaceWidth > widthHint * SURFACE_MAX_RATIO) {
      playSurfaceWidth = (int) (widthHint * SURFACE_MAX_RATIO);
      playSurfaceHeight = (int) (playSurfaceWidth / mPlayAspectRatio);
    }
    playSurfaceParams.topMargin = Math.max(0, (heightHint - playSurfaceHeight) / 2);
    playSurfaceParams.height = playSurfaceHeight;
    playSurfaceParams.width = playSurfaceWidth;
    measureChildWithMargins(mLivePlaySurfaceView, widthMeasureSpec, 0, heightMeasureSpec, 0);
    mLivePlayLoadingView.getLayoutParams().height = LayoutParams.MATCH_PARENT;
    mLivePlayLoadingView.getLayoutParams().width = playSurfaceWidth;
    measureChildWithMargins(mLivePlayLoadingView, widthMeasureSpec, 0, heightMeasureSpec, 0);

    //直播辅助功能工具栏
    final int itemSquareSize = heightHint / assistantToolbarItems.length - separatorSize;
    LayoutParams assistantItemParams;
    View assistantItemView;
    final int lastIndex = assistantToolbarItems.length - 1;
    for (int i = 0; i < assistantToolbarItems.length; i++) {
      assistantItemView = assistantToolbarItems[i];
      assistantItemParams = (LayoutParams) assistantItemView.getLayoutParams();
      assistantItemParams.width = itemSquareSize;
      assistantItemParams.height = itemSquareSize;
      assistantItemParams.topMargin = i * (itemSquareSize + separatorSize);
      assistantItemParams.leftMargin = playSurfaceWidth;
      measureChildWithMargins(assistantItemView, widthMeasureSpec, 0, heightMeasureSpec, 0);
      if (i != lastIndex) {
        assistantItemSeparators[i][0] = assistantItemParams.leftMargin;
        assistantItemSeparators[i][1] = assistantItemParams.topMargin + itemSquareSize;
        assistantItemSeparators[i][2] = assistantItemParams.leftMargin + itemSquareSize;
        assistantItemSeparators[i][3] = assistantItemParams.topMargin + itemSquareSize
            - separatorSize;
      } else {
        assistantItemSeparators[lastIndex][0] = assistantItemParams.leftMargin + itemSquareSize;
        assistantItemSeparators[lastIndex][1] = 0;
        assistantItemSeparators[lastIndex][2] = assistantItemParams.leftMargin + itemSquareSize;
        assistantItemSeparators[lastIndex][3] = heightHint;
      }
    }

    //播放按钮
    measureChildWithMargins(mLivePlayStartBtn, widthMeasureSpec, 0, heightMeasureSpec, 0);
    final int playBtnWidth = mLivePlayStartBtn.getMeasuredWidth();
    final int playBtnHeight = mLivePlayStartBtn.getMeasuredHeight();
    LayoutParams btnParams = (LayoutParams) mLivePlayStartBtn.getLayoutParams();
    btnParams.leftMargin = (int) ((widthHint - (playSurfaceWidth + itemSquareSize)
        - playBtnWidth) / 2f + (playSurfaceWidth + itemSquareSize));
    btnParams.topMargin = (heightHint - playBtnHeight) / 2;
    btnParams.gravity = Gravity.NO_GRAVITY;

    measureChildWithMargins(liveStateTip, widthMeasureSpec, 0, heightMeasureSpec, 0);
    final int liveStateTipWidth = liveStateTip.getMeasuredWidth();
    LayoutParams liveStateTipParams = (LayoutParams) liveStateTip.getLayoutParams();
    liveStateTipParams.topMargin = btnParams.topMargin + btnParams.height + liveStateTipTopMargin;
    liveStateTipParams.leftMargin = (int) ((widthHint - (playSurfaceWidth + itemSquareSize)
        - liveStateTipWidth) / 2f + (playSurfaceWidth + itemSquareSize));
    liveStateTipParams.gravity = Gravity.NO_GRAVITY;

    setMeasuredDimension(resolveSize(widthHint, widthMeasureSpec),
        resolveSize(heightHint, heightMeasureSpec));
  }

  private void measureVertical(int widthHint, int heightHint,
                               int widthMeasureSpec, int heightMeasureSpec) {

    //直播录制区域
    final int playSurfaceHeight = (int) (widthHint / mPlayAspectRatio);
    final LayoutParams playSurfaceParams = (LayoutParams) mLivePlaySurfaceView.getLayoutParams();
    playSurfaceParams.height = playSurfaceHeight;
    playSurfaceParams.width = LayoutParams.MATCH_PARENT;
    measureChildWithMargins(mLivePlaySurfaceView, widthMeasureSpec, 0, heightMeasureSpec, 0);
    mLivePlayLoadingView.getLayoutParams().height = playSurfaceHeight;
    mLivePlayLoadingView.getLayoutParams().width = LayoutParams.MATCH_PARENT;
    measureChildWithMargins(mLivePlayLoadingView, widthMeasureSpec, 0, heightMeasureSpec, 0);

    //直播辅助功能工具栏
    final int itemSquareSize = widthHint / assistantToolbarItems.length - separatorSize;
    final int playSurfaceBottomY = playSurfaceParams.topMargin + playSurfaceHeight;
    LayoutParams assistantItemParams;
    View assistantItemView;
    final int lastIndex = assistantToolbarItems.length - 1;
    for (int i = 0; i < assistantToolbarItems.length; i++) {
      assistantItemView = assistantToolbarItems[i];
      assistantItemParams = (LayoutParams) assistantItemView.getLayoutParams();
      assistantItemParams.width = itemSquareSize;
      assistantItemParams.height = itemSquareSize;
      assistantItemParams.topMargin = playSurfaceBottomY;
      assistantItemParams.leftMargin = i * (itemSquareSize + separatorSize);
      measureChildWithMargins(assistantItemView, widthMeasureSpec, 0, heightMeasureSpec, 0);
      if (i != lastIndex) {
        assistantItemSeparators[i][0] = assistantItemParams.leftMargin
            + itemSquareSize;
        assistantItemSeparators[i][1] = assistantItemParams.topMargin;
        assistantItemSeparators[i][2] = assistantItemParams.leftMargin
            + itemSquareSize;
        assistantItemSeparators[i][3] = assistantItemParams.topMargin
            + itemSquareSize - separatorSize;
      } else {
        assistantItemSeparators[lastIndex][0] = 0;
        assistantItemSeparators[lastIndex][1] = assistantItemParams.topMargin
            + itemSquareSize;
        assistantItemSeparators[lastIndex][2] = widthHint;
        assistantItemSeparators[lastIndex][3] = assistantItemParams.topMargin
            + itemSquareSize;
      }
    }

    //播放按钮
    measureChildWithMargins(mLivePlayStartBtn, widthMeasureSpec, 0, heightMeasureSpec, 0);
    final int playBtnHeight = mLivePlayStartBtn.getMeasuredHeight();
    LayoutParams btnParams = (LayoutParams) mLivePlayStartBtn.getLayoutParams();
    btnParams.topMargin = ((heightHint - playSurfaceHeight - playBtnHeight) / 2)
        + playSurfaceHeight;
    btnParams.gravity = Gravity.CENTER_HORIZONTAL;

    measureChildWithMargins(liveStateTip, widthMeasureSpec, 0, heightMeasureSpec, 0);
    LayoutParams liveStateTipParams = (LayoutParams) liveStateTip.getLayoutParams();
    liveStateTipParams.topMargin = btnParams.topMargin + btnParams.height + liveStateTipTopMargin;
    liveStateTipParams.gravity = Gravity.CENTER_HORIZONTAL;

    setMeasuredDimension(resolveSize(widthHint, widthMeasureSpec),
        resolveSize(heightHint, heightMeasureSpec));
  }

  @Override
  protected void dispatchDraw(Canvas canvas) {
    super.dispatchDraw(canvas);
    canvas.setDrawFilter(mAdjustLineDrawFilter);
    for (int[] assistantItemSeparator : assistantItemSeparators) {
      canvas.drawLine(assistantItemSeparator[0],
          assistantItemSeparator[1] + getPaddingTop(),
          assistantItemSeparator[2],
          assistantItemSeparator[3] + getPaddingTop(),
          mSeparatorLinePaint);
    }
  }

  public void setPlayAspectRatio(float playAspectRatio) {
    this.mPlayAspectRatio = playAspectRatio;
  }

  public void ensureLiveStateTip() {
    if (mLivePlayStartBtn == null || liveStateTip == null) {
      return;
    }
    final PlayPauseDrawable playPauseDrawable = mLivePlayStartBtn.getPlayPauseDrawable();
    if (playPauseDrawable.isPlay()) {
      liveStateTip.setText(getResources().getString(R.string.live_pause_tip_text, ""));
    } else {
      liveStateTip.setText(getResources().getString(R.string.live_playing_tip_text, ""));
    }
    setLiveStateTipBackground();
  }

  private void setLiveStateTipBackground() {
    if (shapeDrawable == null) {
      shapeDrawable = new GradientDrawable();
      shapeDrawable.setCornerRadius(30);
    }
    final int color = mLivePlayStartBtn.getColor();
    shapeDrawable.setStroke(2, color);
    liveStateTip.setTextColor(color);
    liveStateTip.setBackground(shapeDrawable);
  }
}





























